﻿using FlyingEye.Common.Utils;
using FlyingEye.Utils;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using Volo.Abp;

namespace FlyingEye.EntityFrameworkCore
{
    public class MySqlDbContextFactory : IDesignTimeDbContextFactory<MySqlDbContext>
    {
        private static string BaseDir => Path.Combine(Directory.GetCurrentDirectory(), "../FlyingEye.DbMigrator/");

        public MySqlDbContext CreateDbContext(string[] args)
        {
            MySqlEfCoreEntityExtensionMappings.Configure();

            var configuration = BuildConfiguration();

            var application = AbpApplicationFactory.Create<MySqlEntityFrameworkCoreModule>(options =>
            {
                options.UseAutofac();
                options.Services.ReplaceConfiguration(configuration);
                options.Services.Configure<ApplicationStartInOptions>(options =>
                {
                    options.StartPath = BaseDir;
                });
            });

            var service = application.Services.BuildAutofacServiceProvider();
            var appConfiguration = service.GetRequiredService<ApplicationConfiguration>();

#if DEBUG
            //var connectionString = appConfiguration.GetMySqlConnectionString("LocalMySql");
            var connectionString = appConfiguration.GetMySqlConnectionString("TestMySql");
#endif
#if RELEASE
                var connectionString = appConfiguration.GetMySqlConnectionString("MySql");
#endif
            Console.WriteLine($"ConnectionString is {connectionString}");

            var builder = new DbContextOptionsBuilder<MySqlDbContext>()
                .UseMySql(connectionString, ServerVersion.Parse("8.0"));

            return new MySqlDbContext(builder.Options);
        }

        private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(BaseDir)
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }
    }
}
